var express = require('express');
var router = express.Router();
let user = require('../middleware/user_mid')
const fileUp = require('../utils/fileUtils')
const redisUtils = require('../utils/redisUtils')
/**
 * 用户一级路由
 */
router.get('/', function (req, res, next) {
    res.send('respond with a resource');
});
/**
 * 用户登录验证路由
 */
router.post('/login', function (req, res, next) {
    user.getUserlogin(req, res)
});

/**
 * 用户头像上传一级路由
 */
router.post('/icon', async function (req, res, next) {
    let Userdata = await redisUtils.get("UserloginData")
    let head_imgUrl = await fileUp.upload(req)
    let arr = Userdata.split(',');
    let userdata = JSON.parse(arr)

    req.head_imgUrl = head_imgUrl;
    if (!head_imgUrl) {
        res.send("没有选择图片")
    }
    req.u_id = userdata.id
    user.upUserHead(req, res);

});
/**
 * 修改用户名一级路由
 */
router.post('/upName', async function (req, res) {
    let Userdata = await redisUtils.get("UserloginData")
    let arr = Userdata.split(',');
    let userdata = JSON.parse(arr)
    req.u_id = userdata.id
    user.upUserName(req, res)
})

/**
 * 用户注册一级路由
 */
router.post('/register', function (req, res) {
    user.regist(req, res)
})

router.post('/getHead', function (req, res) {
    user.getUserdata(req, res)
})
router.post('/getUserName', function (req, res) {
    user.getUserName(req, res)
})
router.post('/getUserNameAll', function (req, res) {
    user.getUserNameAll(req, res)
})

router.post('/getUserAll', function (req, res) {
    user.getUserAll(req, res)
})


/**
 图片验证码
 */
var svgCaptcha = require('svg-captcha');
router.get('/getCaptcha', function (req, res, next) {
    console.log("getCaptcha")
    console.log("当前用户为" + JSON.stringify(req.headers.session))
    var captcha = svgCaptcha.create({
        // 翻转颜色
        inverse: false,
        // 字体大小
        fontSize: 36,
        // 噪声线条数
        noise: 2,
        // 宽度
        width: 80,
        // 高度
        height: 30,
    });
    // 保存到session,忽略大小写
    req.session.captcha = captcha.text.toLowerCase();
    // console.log(req.session.captcha); //0xtg 生成的验证码
    //设置什么格式返回前端,默认text格式
    res.setHeader('Content-Type', 'image/svg+xml');
    //将此数据转成字符串写入传到前端,并且.write并不会结束请求可以多次调用
    res.write(String(captcha.data));
    res.end()
})
router.get('/captchaValid', (req, resp) => {
    let captcha = req.query.captcha;
    if (captcha == req.session.captcha) {
        resp.send(captcha)
    } else {
        throw new Error('验证码输入错误')
    }
})


module.exports = router;
